// 地址控制器
import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/common/city_picker.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/entity/user_center/address_list_entity.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/AddressParse.dart';
import 'package:cbec_app/utils/EventMgr.dart';
import 'package:cbec_app/utils/GlobalData.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:cbec_app/utils/logger.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class AddressController extends BaseController {
  var page = 1.obs;

  ///修改的时候使用的id
  String id = '0';

  ///省市区列表
  var provinceList = [].obs;

  ///地址列表
  RxList<AddressListEntity?>? addressList = <AddressListEntity>[].obs;

  ///姓名
  TextEditingController nameTxtCtr = TextEditingController();

  ///手机号
  TextEditingController phoneTxtCtr = TextEditingController();

  ///地址
  TextEditingController addressTxtCtr = TextEditingController();

  ///智能解析地址
  TextEditingController smartParseCtr = TextEditingController();

  ///省id
  late int province;

  ///市id
  late int city;

  ///区id
  late int district;

  ///默认地址
  var isDefault = false.obs;

  var areaText = '省市区县'.obs;
  var provinceTxt = ''.obs;
  var cityTxt = ''.obs;
  var areaTxt = ''.obs;

  ///地址栏参数
  var urlParams = '';

  var areaColor = Tools.fromHex("#999999").obs;

  @override
  void onInit() {
    super.onInit();
    if (Get.parameters != {} && Get.parameters['isSelect'] != null) {
      urlParams = Get.parameters['isSelect']!;
    }

    smartParseCtr.addListener(() {
      var data = AddressParse.parseAddressToCode(smartParseCtr.text);
      nameTxtCtr.value = nameTxtCtr.value.copyWith(text: data['name'] ?? '');
      phoneTxtCtr.value = phoneTxtCtr.value.copyWith(text: data['phone'] ?? '');
      provinceTxt.value = data['provinceName'] ?? '';
      cityTxt.value = data['cityName'] ?? '';
      areaTxt.value = data['areaName'] ?? '';
      if (data['provinceCode'] != null) {
        province = data['provinceCode'];
      }

      if (data['cityCode'] != null) {
        city = data['cityCode'];
      }

      if (data['areaCode'] != null) {
        district = data['areaCode'];
      }

      areaText.value = "${data['provinceName'] ?? ''} ${data['cityName'] ?? ''} ${data['areaName'] ?? ''}";
      areaColor.value = Colors.black;
      addressTxtCtr.value = addressTxtCtr.value.copyWith(text: data['address'] ?? '');
      logger.d('识别结果 $data');
    });

    getAddressList();
    if (GlobalData.provinceCityAreaList.isEmpty) {
      getProvinceCtiyArea();
    }
    EventMgr.on(EventType.refreshAddress, (arg) {
      getAddressList();
    });
  }

  ///获取地址列表
  Future getAddressList() async {
    Tools.showLoading();
    return Network.getAddress().then((value) {
      print(value);
      Tools.hideLoading();
      addressList?.value = value!;
    }).catchError((onError) {
      print(onError);
      Tools.hideLoading();
    });
  }

  ///获取省市区
  void getProvinceCtiyArea() {
    Network.getProvinceCityArea().then((value) {
      GlobalData.provinceCityAreaList = value;
    });
  }

  ///默认地址设置
  void setDefault(bool value) {
    isDefault.value = value;
  }

  ///选择省市区
  void choiseArea(CityResult result) {
    if (result.areaCode == '') {
      result.areaCode = '0';
    }
    areaText.value = "${result.province ?? '北京市'} ${result.city ?? '市辖区'} ${result.area ?? '东城区'}";

    provinceTxt.value = result.province ?? '北京市';
    cityTxt.value = result.city ?? '市辖区';
    areaTxt.value = result.area ?? '东坡区';

    province = int.parse(result.provinceCode ?? '1');
    city = int.parse(result.cityCode ?? '36');
    district = int.parse(result.areaCode ?? "37");
    print("${province} ${city} ${district}");
    areaColor.value = Colors.black;
  }

  ///新建初始化
  void initAdd() {
    id = '0';
    province = 1;
    city = 1;
    district = 1;
    isDefault.value = false;
    nameTxtCtr.text = "";
    addressTxtCtr.text = "";
    phoneTxtCtr.text = "";
    smartParseCtr.text = '';
    areaText.value = "省市区县";
    areaColor.value = Tools.fromHex("#999999");
    Get.toNamed(Routes.addAddress);
  }

  ///保存
  void submit() {
    if (id == '0') {
      //新增
      Tools.showLoading();
      Network.addAddress(province, city, district, isDefault.value == true ? 1 : 0, nameTxtCtr.text, addressTxtCtr.text, phoneTxtCtr.text)
          .then((value) => {
                if (value == true) {Tools.hideLoading(), Get.back(), EventMgr.send(EventType.refreshAddress)}
              })
          .catchError((onError) {
        Tools.hideLoading();
      });
    } else {
      //修改
      Tools.showLoading();
      Network.updateAddress(id, province, city, district, isDefault.value == true ? 1 : 0, nameTxtCtr.text, addressTxtCtr.text, phoneTxtCtr.text)
          .then((value) => {
                if (value == true) {Tools.hideLoading(), Get.back(), EventMgr.send(EventType.refreshAddress)}
              })
          .catchError((onError) {
        Tools.hideLoading();
      });
    }
  }

  ///修改详情
  void updateInfo(AddressListEntity params) {
    smartParseCtr.text = '';
    province = params.province!;
    city = params.city!;
    district = params.district!;
    isDefault.value = params.isDefault == 1 ? true : false;
    nameTxtCtr.text = params.receiveName!;
    addressTxtCtr.text = params.receiveAddress!;
    phoneTxtCtr.text = params.receivePhone!;
    areaText.value = "${params.provinceName} ${params.cityName} ${params.districtName ?? ''}";
    provinceTxt.value = params.provinceName!;
    cityTxt.value = params.cityName!;
    areaTxt.value = params.districtName ?? '';
    areaColor.value = Colors.black;

    id = params.id!;

    Get.toNamed(Routes.addAddress);
  }

  ///删除地址
  void deleteAddress(String id, int index) {
    Network.deleteAddress(id).then((value) => {
          if (value == true)
            {
              Tools.showToast("删除完成"),
              addressList?.remove(addressList?[index]),
            }
        });
  }

  ///点击地址item
  void clickAddressItem(AddressListEntity info) {
    if (urlParams != '') {
      ///执行返回
      EventMgr.send(EventType.selectAddress, info.toJson());
      Get.back();
    }
  }

  @override
  void onPageRefresh() async {
    super.onPageRefresh();
    await getAddressList();
    baseRefreshCtr.refreshCompleted(resetFooterState: true);
  }

  @override
  void onPageLoading() async {
    super.onPageLoading();
    page.value += 1;
    await getAddressList();
    baseRefreshCtr.loadComplete();
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
    EventMgr.off(EventType.refreshAddress);
  }
}
